import { createStore } from 'vuex'

export default createStore({
  state: {
    cartarray: []
  },
  mutations: {
    // 添加商品到购物车
    tocart(state: any, tag: any) {
      const goods: any = state.cartarray.find((value: any) => {
        return value.id === tag.id
      })
      // 如果商品存在
      if(goods) {
        goods.cartCount += 1
      } else {
        const item = {
          id: tag.id,
          title: tag.details,
          cartCount: 1,
          img: tag.img
        }
        state.cartarray.push(item)
      }
    },

    getcart(state: any) {
      console.log(state)
    }, 
    clearCart(state: any) {
      state.cartarray = []
    },
    add(state: any, tag: any) {
      const goods: any = state.cartarray.find((value: any) => {
        return value.id === tag.id
      })
      // 如果商品存在
      if(goods) {
        goods.cartCount += 1
      } else {
        const item = {
          id: tag.id,
          title: tag.title,
          cartCount: 1,
          img: tag.img
        }
        state.cartarray.push(item)
      }
    },
    sub(state: any, val: any) {
      for(let i = 0; i < state.cartarray.length; i++) {
        if(state.cartarray[i].id === val.id) {
          if (state.cartarray[i].cartCount === 1) {
            state.cartarray.splice(i, 1)
          }else {
            state.cartarray[i].cartCount -= 1
          }
        } 
      }
    }
  },
  actions: {
  },
  modules: {
  },
  getters: {
    getGoodsNum(store: any) {
      let num = 0
      store.cartarray.forEach((val: any) => {
        num += val.cartCount
      })
      return num
    }
  }
})
